from datetime import datetime, timedelta
from flask import Blueprint, jsonify, request, session
from models import CouponCode, UserModel
from server.resource.util.ApiResponse import ApiResponse
from exts import db
import string
import random

bp = Blueprint("coupon", __name__, url_prefix="/coupon")


def generate_coupon_code(i,expiry_date, duration, special_signature="KAKAKAKAKAKA"):
    """
    生成兑换码
    """
    expiry_date_str = expiry_date.strftime('%y%m%d')
    return f"{expiry_date_str}{duration:04d}{special_signature}{i}"


@bp.route("/generate", methods=['POST'])
def generate():
    """
    生成兑换码并保存到数据库
    """
    data = request.get_json()
    count = int(data['count'])  # 单次生成兑换码的数量
    period = int(data['period'])  # 有效期，格式应为天数
    duration = int(data['duration'])  # 会员持续期，几天会员

    expiry_date = datetime.now() + timedelta(days=period)
    coupons = []

    for item in range(count):
        code = generate_coupon_code(item,expiry_date, duration)
        # 这里应该包含将生成的兑换码保存到数据库的逻辑
        # 示例：db.session.add(YourCouponModel(code=code, expiry_date=expiry_date, duration=duration))
        couponCode = CouponCode(code=code,expiry_date=expiry_date,duration=duration)
        db.session.add(couponCode)
        db.session.commit()
        coupons.append(code)

    db.session.commit()  # 保存所有新生成的兑换码

    return jsonify(ApiResponse.success(coupons))
@bp.route("/redeem", methods=['POST'])
def redeem():
    """
    核销兑换码
    """
    data = request.get_json()
    coupon_code = data['coupon_code']
    username = data['username']

    # 查询数据库中的兑换码
    # 示例：coupon = YourCouponModel.query.filter_by(code=coupon_code).first()
    coupon = CouponCode.query.filter_by(code=coupon_code).first()

    if coupon and coupon.expiry_date >= datetime.now():
        # 如果兑换码有效，执行核销逻辑，比如更新用户的会员状态
        # user = UserModel.query.filter_by(username=session["username"]).first()
        user = UserModel.query.filter_by(username=username).first()
        user.state = '2'
        user.member_state = '0'
        user.join_member_time = datetime.now() + timedelta(days=coupon.duration)
        db.session.commit()
        return jsonify(ApiResponse.success())
    else:
        return jsonify(ApiResponse.server_error("没有这条验证码哟！！"))
